package cn.sc.summer.core.aspect;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.sc.summer.core.annotation.EnumValid;
import cn.sc.summer.exception.exceptions.CommonException;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author ：a-xin
 * @title ：EnumValidtor
 * @description ：配合注解 @EnumValid验证每个枚举值是否符合枚举类的工具类
 */
@Slf4j
public class EnumValidAspect implements ConstraintValidator<EnumValid, Object> {

    private EnumValid enumValid;

    @Override
    public void initialize(EnumValid enumValid) {
        this.enumValid = enumValid;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (ObjectUtil.isNull(value)) {
            return true;
        }
        Class<?> cls = enumValid.target();
        String arg = enumValid.arg();
        Object[] objects = cls.getEnumConstants();
        for (Object obj : objects) {
            try {
                Object getArg = obj.getClass().getMethod("get" + CharSequenceUtil.upperFirst(arg)).invoke(obj);
                if (ObjectUtil.equals(value, getArg)) {
                    return true;
                }
            } catch (Exception e) {
                throw new CommonException(enumValid.message(), e);
            }
        }
        return false;
    }

}
